import React, { useContext, useState, useEffect, useRef } from 'react';
import { Input, Form, Select, Empty } from 'antd';
// @ts-ignore
import { getMessage } from '@inbiz/react';
import { EditableContext } from './SetVariableDrawer';

interface Item {
  createTime: string;
  id: string;
  moveControl: string;
  moveControlId: string;
  pcControl: string;
  pcControlId: string;
  ralationId: string;
  ralationName: string;
  remark: string;
  type: string;
  varName: string;
}

// 可修改表格组件-行
const EditableRow = (props: any) => <tr {...props} />;

interface EditableCellProps {
  title: React.ReactNode;
  editable: boolean;
  children: React.ReactNode;
  dataIndex: string;
  record: Item;
  variateId: string;
  pcControl?: any[];
  h5Control?: any[];
  required: boolean;
  setNowKey: (b: string) => void;
  handleSave: (record: Item) => void;
  variateList: any[];
}

// 可修改表格组件-列（单元格）
const EditableCell = ({
  title,
  editable,
  children,
  dataIndex,
  record,
  required,
  variateId,
  pcControl,
  h5Control,
  setNowKey,
  handleSave,
  variateList,
  ...restProps
}: EditableCellProps) => {
  const [editing, $Editing] = useState(false);
  const inputRef = useRef(null);
  const form = useContext(EditableContext)!;

  useEffect(() => {
    if (editing && inputRef.current) {
      let dom: HTMLElement = inputRef.current;
      dom?.focus();
    }
  }, [editing]);

  const toggleEdit = () => {
    setNowKey(record.id);
    $Editing(true);
    form.setFieldsValue({ [dataIndex]: record[dataIndex] });
  };

  const getName = (id: any, isPc: boolean) => {
    let name = '';
    const arr = isPc ? pcControl : h5Control;
    let idx = arr.findIndex((i) => i.value == id);
    if (idx > -1) {
      name = arr[idx].name;
    };
    return name;
  };

  const save = async () => {
    try {
      const values = await form.validateFields();
      let row: any = { ...record };
      if (values.moveControlId) {
        row.moveControl = getName(values.moveControlId, false);
      };
      if (values.pcControlId) {
        row.pcControl = getName(values.pcControlId, true);
      };
      let recordD = { ...row, ...values };
      handleSave(recordD);
    } catch (err) { };
    $Editing(false);
  };

  let childNode = children;

  if (editable) {
    const placeMessage = getMessage('ProcessManagement.placeMessage');
    const setVariate_message = getMessage('ProcessManagement.setVariate_message');
    const setVariate_name_message = getMessage('ProcessManagement.setVariate_name_message');
    childNode =
      editing && variateId === record.id ? (
        <Form.Item
          style={{ margin: 0 }}
          name={dataIndex}
          rules={
            required
              ? dataIndex === 'varName'
                ? [
                  {
                    required: true,
                    message: setVariate_name_message,
                  },
                  {
                    pattern: /^[a-zA-Z][a-zA-Z\d]*$/,
                    message: setVariate_message,
                  },
                ]
                : [
                  {
                    required: true,
                    message: setVariate_name_message,
                  },
                ]
              : []
          }
        >
          {['varName', 'remark'].includes(dataIndex) ? (
            <Input ref={inputRef} onPressEnter={save} onBlur={save} placeholder={placeMessage} />
          ) : ['pcControlId'].includes(dataIndex) ? (
            <Select
              ref={inputRef}
              onBlur={save}
              allowClear
              placeholder={placeMessage}
              getPopupContainer={() => document.body}
              dropdownRender={(menu) => {
                if (pcControl?.length == 0) {
                  return <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description='暂无数据' />
                }
                return menu;
              }}
            >
              {pcControl.map((item: any) => {
                return <Select.Option value={item.value}>{item.name}</Select.Option>;
              })}
            </Select>
          ) : ['moveControlId'].includes(dataIndex) ? (
            <Select
              ref={inputRef}
              onBlur={save}
              allowClear
              placeholder={placeMessage}
              getPopupContainer={() => document.body}
              dropdownRender={(menu) => {
                if (h5Control?.length == 0) {
                  return <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description='暂无数据' />
                }
                return menu;
              }}
            >
              {h5Control.map((item: any) => {
                return <Select.Option value={item.value}>{item.name}</Select.Option>;
              })}
            </Select>
          ) : null}
        </Form.Item>
      ) : (
        <div
          className="editable-cell-value-wrap"
          id={`cell-${dataIndex}-${record.id}`}
          onClick={toggleEdit}
          // @ts-ignore
          title={children || ''}
        >
          {children}
        </div>
      );
  }

  return <td {...restProps}>{childNode}</td>;
};

export { EditableRow, EditableCell };
